package com.glq1218.service.impl;

import com.glq1218.domain.vo.LoginVo;
import com.glq1218.domain.vo.UserInfoVo;
import com.glq1218.response.ResponseResult;
import com.glq1218.security.CustomUserDetails;
import com.glq1218.security.authentication.email.EmailAuthenticationToken;
import com.glq1218.security.authentication.phone.PhoneAuthenticationToken;
import com.glq1218.service.LoginService;
import com.glq1218.util.JwtUtils;
import com.glq1218.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public ResponseResult<UserInfoVo> login(LoginVo loginVo) {
        String account = loginVo.getAccount();
        if (!StringUtils.hasText(account)) {
            return ResponseResult.error("账号不能为空");
        }
        Authentication authentication = null;
        switch (loginVo.getType()) {
            // 0 用户名登录
            case 0: {
                authentication = authenticationManager
                        .authenticate(UsernamePasswordAuthenticationToken
                                .unauthenticated(account, loginVo.getPassword()));
                break;
            }
            // 1 手机号登录
            case 1: {
                authentication = authenticationManager
                        .authenticate(PhoneAuthenticationToken
                                .unauthenticated(account, loginVo.getVerificationCode()));
                break;
            }
            // 2 邮箱登录
            case 2: {
                authentication = authenticationManager
                        .authenticate(EmailAuthenticationToken
                                .unauthenticated(account, loginVo.getVerificationCode()));
                break;
            }
            default: {
                return ResponseResult.error("未指定登录类型");
            }
        }
        // 从loadUserByUsername方法中查到该用户的信息, 封装到UserDetails,
        // 之后又塞到了UsernamePasswordAuthenticationToken的Principal属性中
        assert authentication != null;
        CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
        String username = userDetails.getUsername();
        String token = JwtUtils.createToken(username);
        // 把token存入redis中
        redisUtils.set("token:" + username, token);
        return ResponseResult.success("登录成功", new UserInfoVo(userDetails.getUser(), token));
    }
}
